import type { FormInstance, FormRules } from 'element-plus'
import { onMounted, reactive, ref, toRaw } from 'vue'

export default function useApply() {
  const formRef = ref<FormInstance>()
  const isLoading = ref(false)
  const formData = reactive({
    deptName: '',
    name: '',
    phone: '',
    address: '',
    email: '',
    scenario: '',
    period: ['', ''] as any,
  })
  const validationRules: FormRules = {
    deptName: [{ required: true, message: '请输入申请单位' }],
    name: [{ required: true, message: '请输入申请人' }],
    phone: [
      { required: true, message: '请输入联系电话' },
      {
        pattern: /^((0\d{2,3}-\d{7,8})|(1[345678]\d{9}))$/,
        message: '请输入固话或手机号',
        trigger: ['blur', 'change'],
      },
    ],
    address: [{ required: true, message: '请输入联系地址' }],
    email: [
      { type: 'email', message: '请输入正确的邮箱地址' },
      {
        required: true,
        message: '请输入邮箱地址',
      },
      {
        min: 6,
        max: 50,
        message: '长度在 6 到 50 个字符',
        trigger: 'blur',
      },
    ],
    scenario: [{ required: true, message: '请输入使用场景' }],
  }
  const attachments = ref<
    {
      /** 文件名 */ fileName: string
      /** 文件路径 */
      filePath: string
      /** 文件大小 */
      fileSize?: number
      /** 文件后缀 */
      fileSuffix?: string
    }[]
  >([])

  /** 查询列表 */
  async function onSearch() {}

  /** 提交表单 */
  async function onSubmit() {
    formRef.value.validate((valid) => {
      console.log('🚀 ~ file: useApply.ts:51 ~ onSubmit ~ valid:', valid)
      if (!valid) return
      console.log(toRaw(formData))
    })
  }

  /** 重置新增的表单  */
  function resetForm() {
    formRef.value.resetFields()
  }

  onMounted(() => {
    onSearch()
  })

  return {
    isLoading,
    formData,
    attachments,
    validationRules,
    formRef,
    resetForm,
    onSubmit,
    onSearch,
  }
}
